<?php

namespace App\Console\Commands\WorkOrder;

use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\ConfigModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\WorkOrder\Web\ApplyService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class AutoFuyouSuccess extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workOrder:autoFuyouSuccess';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '工单-富友流程完成自动修改工单为完成状态';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     * @throws ValidationException
     */
    public function handle()
    {
        $config = ConfigModel::getAutoFuyouSwitchConfig() ?? [];
        $switch = $config['switch'] ?? false;
        if (!$switch) {// 增加富友流程完成自动修改工单开关判断
            $this->info('富友流程完成自动修改工单开关未开');
            return 1;
        }
        WorkOrderApplyMainModel::query()
            ->with(
                [
                    'fuyouInfoRel'           => function ($query) {
                        $query->orderByDesc('id');
                    },
                    'openShopMainProcessRel' => function ($q) {
                        $q->with(
                            [
                                'signOrderRel.contractRel',
                                'openShopSiteLocationRel'
                            ]
                        );
                    }
                ]
            )
            ->where('problemPid', OrderEnum::PROBLEM_PID_5)
            ->where('problemChildId', OrderEnum::PROBLEM_PID_5_CHILDREN_105)//夸父收银进件2.0
            ->where('status', OrderEnum::MAIN_STATUS_ING)                //1进行中
            ->whereIn('step', [MissionEnum::STEP_7, MissionEnum::STEP_8])//工单流程状态
            ->chunkById(
                100, function ($workOrderApplyMainModel) {
                foreach ($workOrderApplyMainModel as $workOrderApplyMain) {
                    $mode = $workOrderApplyMain->openShopMainProcessRel->signOrderRel->contractRel->mode ?? 0;
                    // 非分账模式工单 判断商家认证状态&密钥&订单前缀绑定完成-即自动完成工单
                    if ($mode == OpenShopContractTemplateModel::MODE_2) {
                        continue;
                    }
                    $shopId                 = $workOrderApplyMain->shopId ?? 0;                               //门店id
                    $weChatAuthorizeStatus  = $workOrderApplyMain->fuyouInfoRel->weChatAuthorizeStatus ?? 0;  //微信授权状态 0待认证 1成功
                    $alipayAuthorizeStatus  = $workOrderApplyMain->fuyouInfoRel->alipayAuthorizeStatus ?? 0;  //支付宝授权状态 0待认证 1成功
                    $mchKey                 = $workOrderApplyMain->fuyouInfoRel->mchKey ?? '';                //富友商户交易密码
                    $orderPrefix            = $workOrderApplyMain->fuyouInfoRel->orderPrefix ?? '';           //富友商户交易前缀
                    $secondaryBindingStatus = $workOrderApplyMain->fuyouInfoRel->secondaryBindingStatus ?? 0; //富友一二级绑定邮件状态 0待认证 1成功
                    $preSystemApplyStatus   = $workOrderApplyMain->fuyouInfoRel->weChatAuthorizeStatus ?? 0;  //富友前置系统申请邮件状态 0待认证 1成功
                    if (!($shopId && $weChatAuthorizeStatus && $alipayAuthorizeStatus && $mchKey && $orderPrefix
                        && $secondaryBindingStatus && $preSystemApplyStatus)) {
                        continue;
                    }
                    $shopInfo  = (object)current((new RmsShopApi())->getShopByIds([$shopId])["data"]["shopList"]);
                    $paymentId = $shopInfo->shop_fu_you_payments_rel['id'] ?? 0;//店铺支付配置表id
                    $this->info(
                        'workOrderNo:' . $workOrderApplyMain->workOrderNo .
                        ' paymentId:' . $paymentId
                    );

                    // 工单完成处理
                    ApplyService::addFuyouInfo('', 1, $workOrderApplyMain->workOrderNo);
                    // RMS同步门店富友绑定
                    $data = [];
                    if ($paymentId) {
                        $data = [
                            'mchId'            => $workOrderApplyMain->fuyouInfoRel->fyMchntCd ?? '',       //富友商户号
                            'mchKey'           => $mchKey,                                                  //富友商户交易密码
                            'mchName'          => $workOrderApplyMain->fuyouInfoRel->mchName ?? '',         //富友商户用户名
                            'mchPassword'      => $workOrderApplyMain->fuyouInfoRel->mchPassword ?? '',     //富友商户密码
                            'orderPrefix'      => $orderPrefix,                                             //富友商户交易前缀
                            'reservedFyTermId' => $workOrderApplyMain->fuyouInfoRel->reservedFyTermId ?? '',//富友终端号
                            'source'           => 1,
                            'uid'              => 0,
                        ];
                        RmsShopRemote::shopFuYouPaymentsEdit($shopId, $paymentId, $data);
                    }
                    Log::info(
                        'workOrder:autoFuyouSuccess', [
                            'workOrderNo' => $workOrderApplyMain->workOrderNo,
                            'shopId'      => $workOrderApplyMain->shopId,
                            'data'        => $data,
                            'msg'         => '工单完成自动处理',
                        ]
                    );
                    sleep(1);
                }
            }
            );
    }
}
